/*
 * This file is Copyright 2002-2006 Loyola University Chicago,
 * Department of Computer Science and the Emerging Technologies Laboratory.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License via
 *    http://www.apache.org/licenses/LICENSE-2.0.
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.citep.web.admin.transactions.client;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import com.citep.web.gwt.module.BasePresentation;
import com.citep.web.gwt.module.Presentation;
import com.citep.web.gwt.widgets.EditableAccountPanel;
import com.citep.web.gwt.widgets.Shortcut;
import com.citep.web.gwt.widgets.ShortcutTable;
import com.citep.web.gwt.widgets.StatusLabel;
import com.citep.web.gwt.widgets.StepPanel;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.Hyperlink;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.user.client.ui.FormPanel;
import com.google.gwt.user.client.ui.FormHandler;
import com.google.gwt.user.client.ui.FormSubmitCompleteEvent;
import com.google.gwt.user.client.ui.FormSubmitEvent;
import com.google.gwt.user.client.ui.FileUpload;
import com.google.gwt.user.client.ui.ClickListener;
import com.google.gwt.user.client.Window;

public class TransactionImportPresentation extends BasePresentation implements Presentation {

	public void displayError(String key, String value) {
		if(key == null || key.length() < 1)
			Window.alert(value);
	}

	public void displayStatus(String msg, int seconds) {
		if(msg.length() > 1) {
			getStatusLabel().setText(msg);
			getStatusLabel().show(seconds);
		} else {
			getStatusLabel().hide();
		}
	}

	protected TransactionImportApplication application;
	
	protected Label titleLabel;
	protected StatusLabel statusLabel;
	protected VerticalPanel mainPanel;
	protected ShortcutTable shortcuts;
	protected FileUpload fileUpload;
	protected FormPanel uploadPanel;
	
	//the current step we are in
	protected StepPanel currentStep = null;
	
	protected Button createUserButton;	

	protected FileImport fileImportPanel = new FileImport();
	protected EntryReview entryReviewPanel = new EntryReview();
	
	public TransactionImportPresentation() {
		currentStep = fileImportPanel;
	}
	
	public void setApplication(TransactionImportApplication application) {
		this.application = application;
	}	
	
	public void disableCurrentStep() {
		currentStep.setEnabled(false);
	}

	public void enableCurrentStep() {
		currentStep.setEnabled(true);
	}
	
	public void showFileImport() {
		if(currentStep != fileImportPanel) {
			mainPanel.remove(currentStep);
			currentStep = fileImportPanel;
			mainPanel.add(currentStep);
			currentStep.setEnabled(true);
		}
	}
	
	public void showEntryReview() {
		if(currentStep != entryReviewPanel) {
			mainPanel.remove(currentStep);
			currentStep = entryReviewPanel;
			mainPanel.add(currentStep);			
		}
	}
	
	public void moveToNextStep() {
		if(currentStep == fileImportPanel)
			showEntryReview();
		else
			showFileImport();
	}
	
	public Label getTitleLabel() {
		if(titleLabel == null) {
			titleLabel = new Label("Import transactions");
			titleLabel.setStyleName("form_title");
		}
		
		return titleLabel;
	}
	
	public StatusLabel getStatusLabel() {
		if(statusLabel == null) {
			statusLabel = new StatusLabel();
			statusLabel.setStyleName("status_label_small");
			statusLabel.setVisible(false);
		}

		return statusLabel;
	}
	
	protected FileUpload getFileUpload() {
		if(fileUpload == null) {
			fileUpload = new FileUpload();
			fileUpload.setName("import_file");
			fileUpload.setStyleName("form_button");
		}
		
		return fileUpload;
	}
	
	protected FormPanel getUploadPanel() {
		if(uploadPanel == null) {
			uploadPanel = new FormPanel();
			uploadPanel.setAction(GWT.getModuleBaseURL() + "/accounts");
			uploadPanel.setEncoding(FormPanel.ENCODING_MULTIPART);
			uploadPanel.setMethod(FormPanel.METHOD_POST);
			
			uploadPanel.add(fileUpload);
		}
		return uploadPanel;
	}
	
	
		
	public void addShortCut(Shortcut s, boolean highlight) {
		shortcuts.addShortcut(s, highlight);
	}
		
	public Widget getMainPanel() {
		if(mainPanel == null) {
			mainPanel = new VerticalPanel();
			mainPanel.setWidth("100%");
			mainPanel.add(getTitlePanel());

			getTitlePanel().setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
			getTitlePanel().add(getStatusLabel());
			mainPanel.setCellHorizontalAlignment(getStatusLabel(), HasHorizontalAlignment.ALIGN_CENTER);
		
			currentStep.setEnabled(true);
			mainPanel.add(currentStep);
			
		}
		return mainPanel;
	}
	
	public Widget getContext() {
		
		VerticalPanel p = new VerticalPanel();
		p.setStyleName("table_center");
		p.setSpacing(0);
		
		shortcuts = new ShortcutTable("Categories",10);
		shortcuts.setMoreLink(new Hyperlink("[more]","accounts_list"));
		
		p.add(shortcuts);
		
		return p;
	}
	
	public void addStatement(int statementNumber,String accountName) {
		entryReviewPanel.addStatement(statementNumber,accountName);
	}
	
	public void clearStatements() {
		entryReviewPanel.clear();
	}
	
	
	private class FileImport extends StepPanel {
		protected FormPanel form;
		protected Button submitUpload;
		
		public void setEnabled(boolean enabled) {
			super.setEnabled(enabled);
			getSubmitUploadButton().setEnabled(enabled);
		}
		
		public FileImport() {
			super();
			setTitle("Step 1");
			setDescription("Please select a file to upload, as well as its file format");

			VerticalPanel formHolder = new VerticalPanel();
			formHolder.setSpacing(5);
			FileUpload upload = new FileUpload();
			upload.setName("importFile");
			formHolder.add(upload);
			formHolder.add(getSubmitUploadButton());
			getForm().setWidget(formHolder);
			
			add(getForm());
		}

		protected Button getSubmitUploadButton() {
			if(submitUpload == null) {
				submitUpload = new Button("Upload");
				submitUpload.addClickListener(new ClickListener() {
					public void onClick(Widget w) {
						form.submit();
					}
				});
			}
			return submitUpload;
		}
		
		public FormPanel getForm() {
			if(form == null) {
				form = new FormPanel();
				form.setAction(GWT.getModuleBaseURL() + "/import");
				form.setEncoding(FormPanel.ENCODING_MULTIPART);
				form.setMethod(FormPanel.METHOD_POST);
				
				form.addFormHandler(new FormHandler() {
					public void onSubmitComplete(FormSubmitCompleteEvent event) {
						application.onUploadComplete(event.getResults());
					}
					
					public void onSubmit(FormSubmitEvent event) {
						displayStatus("Uploading...",0);
						setEnabled(false);
					}
				});
			}
			return form;
		}
	}
	
	private class EntryReview extends StepPanel {
		private HashMap statementWidgets = new HashMap();
		public EntryReview() {

		}
		
		public void addStatement(int statementNumber, String accountName) {
			ImportTransactionsPanel panel = new ImportTransactionsPanel(statementNumber, accountName, application);
			statementWidgets.put(new Integer(statementNumber), panel);
			add(panel);
			
		}
		
		public void removeStatement(int statementNumber) {
			if(statementWidgets.containsKey(new Integer(statementNumber))) {
				ImportTransactionsPanel panel = (ImportTransactionsPanel)statementWidgets.get(new Integer(statementNumber));
				remove(panel);
				statementWidgets.remove(new Integer(statementNumber));
			}
		}
		
		public void clear() {
			Iterator keys = statementWidgets.keySet().iterator();
			while(keys.hasNext()) {
				Integer key = (Integer)keys.next();
				remove((ImportTransactionsPanel)statementWidgets.get(key));
			}
			statementWidgets.clear();
		}
	}
}
